<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* 2017.6.14 magento 数据接口
*/
class PaypalRefund 
{
	
	function __construct()
	{
		$this->CI =& get_instance();
        $this->db = $this->CI->load->database('default', TRUE);
	}


public function PaypalRefund(){
$refundinfo=$this->db->get_where("db_paypal_refund","refund_status='2' and (platfromname='magento' or platfromname='eBay')")->result_array();

foreach ($refundinfo as $value) {
	$shop_id=$value['shop_id'];
    $order_sn=$value['order_sn'];
    $pay_id=$value['pay_id'];
$moneytype=$value['moneytype'];
$order_id= $value['order_id'];

$dshop=$this->getapi($value['platfromname'],$shop_id,$order_id);


$API_UserName=$dshop[0]['api_username'];
$API_Password=$dshop[0]['api_password'];
$API_Signature=$dshop[0]['api_signature'];

// $API_UserName='sales_api1.starwarscos.com';
// $API_Password='GKPPK5HHPS68CERW';
// $API_Signature='AFcWxV21C7fd0v3bYYYRCpSSRl31AyzLklbuwjGCtbDEg30DflQRq6zw';
// Set request-specific fields.
$transactionID = urlencode($value['payid']);
// print_r($dshop);
// echo "<br/>";
// print_r($seldshop);
// echo "<br/>";
// print_r($shop_id);
// echo "<br/>";
// print_r($API_UserName);
// echo "<br/>";
// print_r($API_Password);
// echo "<br/>";
// print_r($API_Signature);
// echo "<br/>";
// print_r($transactionID);
// die;
// exit;
if (empty($transactionID)) {
	//交易id为空回传
	$upsql5="UPDATE db_paypal_refund SET refund_status='4' where pay_id='{$pay_id}';";
$this->db->query($upsql5);
                $imgdata["goods_id"] = $order_id;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'paypal退款日志,paypal交易号为空';
				$imgdata["createUser"] ='auto';
				$this->db->query($this->db->insert_string('db_goods_log', $imgdata));
}

$refundType = urlencode('Partial');  // or 'Partial' 'Full'
$amount=$value['refund_money'];                         // required if Partial.
$memo='';//$value['refund_reason'];                            // required if Partial.
$currencyID = urlencode($moneytype);   // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

// Add request-specific fields to the request string.
$nvpStr = "&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType&CURRENCYCODE=$currencyID";

if(isset($memo)) {
	$nvpStr .= "&NOTE=$memo";
}

if(strcasecmp($refundType, 'Partial') == 0) {
	if(!isset($amount)) {
		exit('Partial Refund Amount is not specified.');
	} else {
		$nvpStr = $nvpStr."&AMT=$amount";
	}
	
	if(!isset($memo)) {
		exit('Partial Refund Memo is not specified.');
	}
}

// Execute the API operation; see the PPHttpPost function above.

$env = 'product';   //sandbox or product
$httpParsedResponseAr =$this->PPHttpPost($API_UserName,$API_Password,$API_Signature,'RefundTransaction', $nvpStr,$env);
// $resjson=json_encode($httpParsedResponseAr);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
//成功退款
//改变 db_order_list 表
$payreturnid=$httpParsedResponseAr['REFUNDTRANSACTIONID'];
$FEEREFUNDAMT=urldecode($httpParsedResponseAr['FEEREFUNDAMT']);
$GROSSREFUNDAMT=urldecode($httpParsedResponseAr['GROSSREFUNDAMT']);
$NETREFUNDAMT=urldecode($httpParsedResponseAr['NETREFUNDAMT']);
$TOTALREFUNDEDAMOUNT=urldecode($httpParsedResponseAr['TOTALREFUNDEDAMOUNT']);
$TIMESTAMP=urldecode($httpParsedResponseAr['TIMESTAMP']);
$CORRELATIONID=$httpParsedResponseAr['CORRELATIONID'];
$REFUNDSTATUS=$httpParsedResponseAr['REFUNDSTATUS'];
$PENDINGREASON=$httpParsedResponseAr['PENDINGREASON'];
$BUILD=$httpParsedResponseAr['BUILD'];
$upsql2="UPDATE db_order_list SET is_backpay='3' where order_sn='{$order_sn}';";
$this->db->query($upsql2);
	            $imgdata["goods_id"] = $order_id;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = '退款成功,paypal退款流水号：'.$payreturnid;
				$imgdata["createUser"] ='auto';
				$this->db->query($this->db->insert_string('db_goods_log', $imgdata));
$upsql3="UPDATE db_paypal_refund SET refund_status='3' where pay_id='{$pay_id}';";
$this->db->query($upsql3);


$upsql4="UPDATE db_paypal_refund SET payreturnid='{$payreturnid}',FEEREFUNDAMT='{$FEEREFUNDAMT}',GROSSREFUNDAMT='{$GROSSREFUNDAMT}',NETREFUNDAMT='{$NETREFUNDAMT}',TOTALREFUNDEDAMOUNT='{$TOTALREFUNDEDAMOUNT}',TIMESTAM='{$TIMESTAMP}',CORRELATIONID='{$CORRELATIONID}',REFUNDSTATUS='{$REFUNDSTATUS}',PENDINGREASON='{$PENDINGREASON}',BUILD='{$BUILD}' where pay_id='{$pay_id}';";
$this->db->query($upsql4);
	//print_r($httpParsedResponseAr);
	//exit('Refund Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else  {
//退款失败
	            $resjson=urldecode($httpParsedResponseAr['L_LONGMESSAGE0']);
                $imgdata["goods_id"] = $order_id;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = '退款失败'.urldecode($resjson);
				$imgdata["createUser"] ='auto';
				$this->db->query($this->db->insert_string('db_goods_log', $imgdata));

$upsql6="UPDATE db_paypal_refund SET refund_status='4',paypal_fail='{$resjson}' where pay_id='{$pay_id}';";
$this->db->query($upsql6);
//print_r($httpParsedResponseAr);
	//exit('RefundTransaction failed: ' . print_r($httpParsedResponseAr, true));
}

}


$this->returne();


}


/**
 * Send HTTP POST Request
 *
 * @param     string     The API method name
 * @param     string     The POST Message fields in &name=value pair format
 * @return     array     Parsed HTTP Response body
 */
function PPHttpPost($API_UserName,$API_Password,$API_Signature,$methodName_, $nvpStr_, $env) {

 // Set up your API credentials, PayPal end point, and API version.
 $API_UserName = urlencode($API_UserName);
 $API_Password = urlencode($API_Password);
 $API_Signature = urlencode($API_Signature);
 
 if("sandbox" === $env)
 	$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
 else
 	$API_Endpoint = "https://api-3t.paypal.com/nvp";
	
 $version = urlencode('119');

 // Set the curl parameters.
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
 curl_setopt($ch, CURLOPT_VERBOSE, 1);

 // Turn off the server and peer verification (TrustManager Concept).
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);

 // Set the API operation, version, and API signature in the request.
 $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

 // Set the request as a POST FIELD for curl.
 curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

 // Get response from the server.
 $httpResponse = curl_exec($ch);

 if(!$httpResponse) {
 	exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
 }

 // Extract the response details.
 $httpResponseAr = explode("&", $httpResponse);

 $httpParsedResponseAr = array();
 foreach ($httpResponseAr as $i => $value) {
	 $tmpAr = explode("=", $value);
	 if(sizeof($tmpAr) > 1) {
	 	$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
	 }
 }

 if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
 	exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
 }

 return $httpParsedResponseAr;
}



public function getapi($platfromname,$shop_id,$orderid){
if ($platfromname=='magento') {
	$seldshop="select * from db_paypal_account where shopid like'[{$shop_id},%' or shopid like '%,{$shop_id},%' or shopid like '%,{$shop_id}]';";
$dshop=$this->db->query($seldshop)->result_array();
return $dshop;
}

if ($platfromname=='eBay') {
	$selpay="select * from db_order_list where order_id='{$orderid}';";
	$selpaya=$this->db->query($selpay)->result_array();
	$payacc=$selpaya[0]['payaccount'];
	$selapi="select * from db_paypal_account where pay_account='{$payacc}';";
	$dshop=$this->db->query($selapi)->result_array();
return $dshop;
}

}



public function returne(){
$sql1="select * from db_paypal_refund where platfromname='magento' and refund_status='3' and is_comeback='0';";
$retarr=$this->db->query($sql1)->result_array();
foreach ($retarr as $value) {
	$order_id=$value['order_id'];
	$payreturnid=$value['payreturnid'];
	$refund_money=urlencode($value['refund_money']);
	$refund_reason=urlencode($value['refund_reason']);
	$refund_time=urlencode($value['refund_time']);
	$shop_id=$value['shop_id'];
	//查询认证信息
$sql2="select * from d_shop where id='{$shop_id}';";
$refundinfo=$this->db->query($sql2)->result_array();
$datax=json_decode($refundinfo[0]['amazonkey'],true);
$platfrom=$datax['magentotoken'];
//查询订单信息
$sql3="select * from db_order_list where order_id='{$order_id}';";
$list=$this->db->query($sql3)->result_array();
$orderid=$list[0]['tradeid'];

//回传

$url="https://network.pokemoncos.com/data/paypalreturn.php?refund_money={$refund_money}&refund_reason={$refund_reason}&refund_time={$refund_time}&platfrom={$platfrom}&orderid={$orderid}&payreturnid={$payreturnid}";

file_get_contents($url);

$upsql6="UPDATE db_paypal_refund SET is_comeback='1' where order_sn='{$order_sn}';";
$this->db->query($upsql6);

}





}


//获取所有paypal的交易信息记录
public function getpaypalnotes(){
	//遍历数据库paypal账户信息
	$sql="select * from `db_paypal_account`;";
	$res=$this->db->query($sql)->result_array();
	//循环获取paypal账户信息
	foreach ($res as $value) {
		$this->oneaccountnotes($value['pay_id'],$value['pay_account'],$value['api_username'],$value['api_password'],$value['api_signature']);
	}
}

//根据getpaypaalnotes函数的账户信息，分别获取每个账户在固定时间内的交易记录
public function oneaccountnotes($pay_id,$pay_account,$API_UserName,$API_Password,$API_Signature){
	//设置时区为UTC
	date_default_timezone_set('UTC');
	//检索时间范围
	$time=time()-3600*5;
	$pay_id_arr=array('2','4','46','47','48','49','50','51');
	if(in_array($pay_id, $pay_id_arr)) $time=time()-3600*24*50;
	$startdate=date('Y-m-d',$time).'T'.date('H:i:s',$time).'Z';
	$nvpStr="&STARTDATE={$startdate}&TRANSACTIONCLASS=All";
	$env = "product";
	$httpParsedResponseAr = $this->PPHttpPost($API_UserName,$API_Password,$API_Signature,'TransactionSearch', $nvpStr,$env);
	//获取明细
	$res=json_decode(urldecode(json_encode($httpParsedResponseAr)),true);
	//var_export($res);
	for ($i=0; $i <100 ; $i++) { 
		  $TYPE='L_TYPE'.$i;
          $on=isset($res[$TYPE])?1:0;
          if($on==0) return $pay_account.':此账户本次无数据';
          //把对应数据存入数据库中，先检查数据库是否存在此数据，订单状态是否有改变，如果没有改变则跳过，如果有改变则重新录入。
          //交易发生的日期和时间。
          $L_TIMESTAMP='L_TIMESTAMP'.$i;
          //交易时区
          $L_TIMEZONE='L_TIMEZONE'.$i;
          //交易类型 Currency Conversion (credit),Currency Conversion (debit),Payment,Recurring Payment,Temporary Hold,Transfer,Donation
          $L_TYPE='L_TYPE'.$i;
          //买方或付款方（“收款人”）的电子邮件地址。如果支付金额为正值，则该字段是资金的接收者。如果付款为负数，则该字段为付款买家。
          $L_EMAIL='L_EMAIL'.$i;
          //显示买方的名称。
          $L_NAME='L_NAME'.$i;
          //商家的交易ID。
          $L_TRANSACTIONID='L_TRANSACTIONID'.$i;
          //交易的状态 Pending Processing  Success Denied Reversed 
          $L_STATUS='L_STATUS'.$i;
          //总收费总额，包括任何配置文件运输成本和税收。
          $L_AMT='L_AMT'.$i;
          //货币单位
          $L_CURRENCYCODE='L_CURRENCYCODE'.$i;
          //paypal为交易收取的费用。
          $L_FEEAMT='L_FEEAMT'.$i;
          //交易净额。
          $L_NETAMT='L_NETAMT'.$i;
          unset($indata);
          $indata=array();
          $indata['pay_id']=$pay_id;
          $indata['pay_account']=$pay_account;
          $indata['TIMESTAMP']=$res[$L_TIMESTAMP];
          $indata['TIMEZONE']=$res[$L_TIMEZONE];
          $indata['TYPE']=$res[$L_TYPE];
          if(isset($res[$L_EMAIL])){
             $indata['EMAIL']=$res[$L_EMAIL];
          }else{
             $indata['EMAIL']='';
          }
          if(isset($res[$L_NAME])){
          	$indata['NAME']=$res[$L_NAME];
          }else{
          	$indata['NAME']='';
          }
          $indata['TRANSACTIONID']=$res[$L_TRANSACTIONID];
          $indata['STATUS']=$res[$L_STATUS];
          $indata['AMT']=$res[$L_AMT];
          $indata['CURRENCYCODE']=$res[$L_CURRENCYCODE];
          $indata['FEEAMT']=$res[$L_FEEAMT];
          $indata['NETAMT']=$res[$L_NETAMT];
          //需要导入的信息整理完毕，判断是否需要重新导入
          $sql="select * from `db_paypal_notes` where `TRANSACTIONID`='{$indata['TRANSACTIONID']}' and `STATUS`!='{$indata['STATUS']}';";
          $res=$this->db->query($sql)->result_array();
          foreach ($res as $value) {
            $desql="DELETE FROM `db_paypal_notes` where `pn_id`='{$value['pn_id']}';";
            $this->db->query($desql);
          }
          //插入数据库
          $this->db->insert("db_paypal_notes",$indata);

	}
}


//paypal 核对账户上的退款信息和本地退款信息， 把本地没有的添加上来。
public function paypalcheck($list){
//由于ebay paypal账号过多，把原本根据平台名称的改为根据paypalid来，每次同步5个账户
//一次检查一个平台的paypal，
	$list1=0+($list-1)*5;
$sql="select * from db_paypal_account limit {$list1},5;";
$res=$this->db->query($sql)->result_array();
//把获取到的api信息循环
foreach ($res as $value) {
	//循环导入到paypal 退款list函数
	$this->paypalreversedlist($value['pay_id'],$value['api_username'],$value['api_password'],$value['api_signature']);
	
}

}

//paypal退款列表函数
public function paypalreversedlist($pay_id,$API_UserName,$API_Password,$API_Signature){
	//测试数据
// $API_UserName='cosplaysky2017_api1.hotmail.com';
// $API_Password='M729YXJD49G6CB92';
// $API_Signature='AFcWxV21C7fd0v3bYYYRCpSSRl31Asc05dA3A0o8Uyb-9oUykAH4QvEe';
  //使用PPHttpPost函数获取列表
	//设置时区为UTC标准时间
	date_default_timezone_set('UTC');
	//date_default_timezone_get();
	//查询时间
$time=time()-3600*5;//设置检索时间为当前时间之前5小时，
	$pay_id_arr=array('2','4','46','47','48','49','50','51');
	if(in_array($pay_id, $pay_id_arr)) $time=time()-3600*24*50;
$startdate=date('Y-m-d',$time).'T'.date('H:i:s',$time).'Z';
$enddate=date('Y-m-d').'T'.date('H:i:s').'Z';
$nvpStr="&STARTDATE={$startdate}&ENDDATE={$enddate}&TRANSACTIONCLASS=All";
$env = 'product';   //sandbox or product
$httpParsedResponseAr = $this->PPHttpPost($API_UserName,$API_Password,$API_Signature,'TransactionSearch', $nvpStr,$env);
//获取到退款列表
$res=json_decode(urldecode(json_encode($httpParsedResponseAr)),true);

for ($i=0; $i <100 ; $i++) { 
  $TYPE='L_TYPE'.$i;
  $on=isset($res[$TYPE])?1:0;
  if($on==0) return 'list 循环结束';
  //跳过费用相关的
  if($res[$TYPE]!='Refund') continue;
  $STATUS='L_STATUS'.$i;
  //状态不是完成的跳过
  // if($res[$STATUS]!='Refunded') continue;
  //获取paypal的交易号
  $TRANSACTIONID='L_TRANSACTIONID'.$i;
  //通过退款交易号来查询在db_paypal_refund表中是否已存在，
  $is=$this->isinrefund($res[$TRANSACTIONID]);
  if($is==1) continue;
  
  //通过paypal交易号查找这比交易详情
  $this->paypaldetails($res[$TRANSACTIONID],$API_UserName,$API_Password,$API_Signature);
}

}

//获取是否在db_paypal_refund表中已存在
public function isinrefund($payreturnid){
$sql="select * from db_paypal_refund where payreturnid='{$payreturnid}';";
$res=$this->db->query($sql)->result_array();
if(empty($res)) return 0;
return 1;
}


//通过paypal交易号查询交易详情
public function paypaldetails($TRANSACTIONID,$API_UserName,$API_Password,$API_Signature){
 $nvpStr="&TRANSACTIONID=$TRANSACTIONID";
 $env = 'product'; 
 $httpParsedResponseAr =$this->PPHttpPost($API_UserName,$API_Password,$API_Signature,'GetTransactionDetails', $nvpStr,$env);
 $res=json_decode(urldecode(json_encode($httpParsedResponseAr)),true);
 //根据订单交易号查询订单信息。
 if(empty($res['PARENTTRANSACTIONID'])) return '无父级id无法追踪';
 $data=$this->getorder($res['PARENTTRANSACTIONID']);
 //判断查询下来的是否有数据，
 if(gettype($data)!='array') return 0;
 $nowtime=time();
 //把数据插入到数据库中
 $indata=array();
 //订单编号
 $indata['order_sn']=$data['order_sn'];
 //提出退款时间
 $indata['refund_time']=$nowtime;
 //退款金额
 $indata['refund_money']=abs($res['AMT']);
 //确认退款时间
 $indata['confirm_time']=$nowtime;
 //退款状态。3，表示退款成功
 $indata['refund_status']=3;
 //店铺id
 $indata['shop_id']=$data['shopid'];
 //物流名称
 $indata['shipping_name']=$data['shipping_name'];
 //物流单号
 $indata['shipping_number']=$data['shipping_number'];
 //paypal交易号,这个地方指的就是PARENTTRANSACTIONID
 $indata['payid']=$res['PARENTTRANSACTIONID'];
 //退款成功返回id
 $indata['payreturnid']=$TRANSACTIONID;
 //订单原始金额
 $indata['goods_originask']=$data['goods_originask'];
 //订单人民币金额
 $indata['goods_amount']=$data['goods_amount'];
 //订单货币种类
 $indata['moneytype']=$data['moneytype'];
 //订单时间
 $indata['ordertime']=$data['ordertime'];
 //店铺负责人
 $indata['shopoper']=$data['shopoper'];
 //平台名称
 $indata['platfromname']=$this->getplatfromname($data['platformID']);
 //店铺名称
 $indata['shopname']=$data['shopname'];
 //订单id
 $indata['order_id']=$data['order_id'];
 //是否返回
 $indata['is_comeback']=0;
 //表示是本地提交的请求还是paypal账户同步下来的请求,1代表从远程同步下来的。默认0
 $indata['is_inpaypal']=1;
 //paypal 时间
 $indata['TIMESTAM']=$res['ORDERTIME'];
 //paypal 退款状态
 $indata['REFUNDSTATUS']=$res['PAYMENTTYPE'];
 //退款原因
 $indata['refund_reason']="paypal直接获取";
 //插入数据库
 $this->db->insert("db_paypal_refund",$indata);
 
}

//根据paypal交易号获取订单详情
public function getorder($payid){
$sql="select * from db_order_list where payid='{$payid}';";
$res=$this->db->query($sql)->result_array();
if(empty($res)) return 0;
return $res[0];

}

//获取平台名称
public function getplatfromname($id){
$sql="select * from db_platform where id='{$id}';";
$res=$this->db->query($sql)->result_array();
if(empty($res)) return 'none';
return $res[0]['name'];

}


}
?>